#include <stdio.h>      // 标准输入输出
#include <unistd.h>     // POSIX标准接口

#include "ohos_init.h"  // 用于初始化服务(services)和功能(features)
#include "cmsis_os2.h"  // CMSIS-RTOS API V2

#include "iot_gpio.h"   // OpenHarmony HAL：IoT硬件设备操作接口-GPIO
#include "iot_i2c.h"    // OpenHarmony HAL：IoT硬件设备操作接口-I2C
#include "iot_errno.h"  // OpenHarmony HAL：IoT硬件设备操作接口-错误代码定义
#include "hi_io.h"      // 海思 Pegasus SDK：IoT硬件设备操作接口-IO


//器件ID
#define I2C_ID 0 
//设置波特率
#define BAUDRATE 9600
//从机地址
#define ADXL345_ADDR 0x53
//上电
#define ADXL345_PWR_ON 0x2D
//数据格式
#define ADXL345_DATA_FORMAT 0x31
//使能中断
#define ADXL345_INT_ENABLE 0x2E
//写地址
#define ADXL345_WRITE (0x53<<1|0)//0xA6
//读地址
#define ADXL345_READ (0x53<<1|1)//0xA7

void setupADXL345()
{
    uint8_t buffer[2];
    uint16_t retval;
    //初始化引脚
    IoTGpioInit(HI_IO_NAME_GPIO_13);
    IoTGpioInit(HI_IO_NAME_GPIO_14);
    //设置为引脚功能为SDA SCL
    hi_io_set_func(HI_IO_NAME_GPIO_13,HI_IO_FUNC_GPIO_13_I2C0_SDA);
    hi_io_set_func(HI_IO_NAME_GPIO_14,HI_IO_FUNC_GPIO_14_I2C0_SCL);

    retval = IoTI2cInit(I2C_ID,BAUDRATE);
    printf("I2C Init Return: %d\n",retval);

    buffer[0]=ADXL345_PWR_ON;
    buffer[1]=0x08;
    retval = IoTI2cWrite(I2C_ID, ADXL345_WRITE, buffer, 2);
    printf("Power Control Write Return: %d\n", retval);
    usleep(5000);

    buffer[0]=0x1E;//偏移量X
    buffer[1]=0x00;
    retval = IoTI2cWrite(I2C_ID, ADXL345_WRITE, buffer, 2);
    printf("Offset X Write Return: %d\n", retval);
    usleep(5000);

    buffer[0]=0x1F;//偏移量Y
    buffer[1]=0x00;
    retval = IoTI2cWrite(I2C_ID, ADXL345_WRITE, buffer, 2);
    printf("Offset Y Write Return: %d\n", retval);
    usleep(5000);

    buffer[0]=0x20;//偏移量Z
    buffer[1]=0x00;
    retval = IoTI2cWrite(I2C_ID, ADXL345_WRITE, buffer, 2);
    printf("Offset Z Write Return: %d\n", retval);
    usleep(5000);

    buffer[0]=ADXL345_DATA_FORMAT;
    buffer[1]=0x0B;
    retval = IoTI2cWrite(I2C_ID, ADXL345_WRITE, buffer, 2);
    printf("Data Format Write Return: %d\n",retval);
    usleep(5000);
    
    
    buffer[0]=ADXL345_INT_ENABLE;
    buffer[1]=0x80;
    retval = IoTI2cWrite(I2C_ID, ADXL345_WRITE, buffer, 2);
    printf("INT_ENABLE Return: %d\n",retval);
    usleep(5000);
}

void readADXL345(int16_t *x,int16_t *y,int16_t *z)
{
    uint8_t buffer[6];
    uint32_t retval;
    int32_t avex=0,avey=0,avez=0;
    buffer[0]=0x32;
    retval = IoTI2cWrite(I2C_ID,ADXL345_WRITE,buffer,1);
    usleep(1000);

    for (int i=0;i<5;i++)
    {
        retval =IoTI2cRead(I2C_ID,ADXL345_READ,buffer,6);//读取6个字节的数据
        avex += (int16_t)((buffer[1] << 8) | buffer[0]); 
        avey += (int16_t)((buffer[3] << 8) | buffer[2]);
        avez += (int16_t)((buffer[5] << 8) | buffer[4]);
        usleep(11.1*1000);
    }

    *x = avex/5;
    *y = avey/5;
    *z = avez/5;
//调整误差
    *x+=1;
    *y+=7;
}